* Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */publicclassSolution{publicTreeNodeinvertTree(TreeNode root){if(root==null){// 节点为空,不处理returnnull;}else{// 节点不为空Tree...
Can you solve this real interview question? Invert Binary Tree - Given the root of a binary tree, invert the tree, and return its root. Example 1: [https://assets.leetcode.com/uploads/2021/03/14/invert1-tree.jpg] Input: root = [4,2,7,1,3,6,9] Outp
root.right = invertTree(tmp);returnroot; } } 3.2 Java实现-非递归 publicclassSolution2{publicTreeNodeinvertTree(TreeNode root){if(root ==null) {returnroot; } Deque<TreeNode> q =newArrayDeque<>(); q.push(root);while(!q.isEmpty()) {TreeNodenode=q.pop();TreeNodetmp=node.left; node....
auto tmp = invertTree(root->left); 将左子树整体 当作一个节点 交换。 最后返回根节点。 /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */classSoluti...
Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 1. 2. 3. 4. 5. to 4 / \ 7 2 / \ / \ 9 6 3 1 1. 2. 3. 4. 5. 解法1: 本质是输的先序遍历 # Definition for a binary tree node. # class TreeNode(object): ...
226-invert-binary-tree code solution1-DFS /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} ...
1.Invert Binary Tree - 二叉树翻转 [递归] 题目概述: Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia:This problem was inspired bythis original tweetbyMax Howell: Google: 90% of our engineers use the software you wrote (Homebrew)...
226. Invert Binary Tree 提交网址:https://leetcode.com/problems/invert-binary-tree/ Total Accepted:84040Total Submissions:186266Difficulty:EasyACrate:45.1% Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to 4 / \ 7 2 / \ / \ 9 6 3 1 ...
func invertTree(root *TreeNode) *TreeNode { if root == nil { return root } queue := []*TreeNode{} queue = append(queue, root) for len(queue) != 0 { node := queue[0] queue = queue[1:] if node.Left != nil { if node.Left.Left != nil || node.Left.Right != nil { ...
publicTreeNode invertTree(TreeNode root) {//树 递归 my if(null!=root){ TreeNode left = invertTree(root.left); TreeNode right = invertTree(root.right); root.left=right; root.right=left; } returnroot; } 非递归的方法 1 2 3